﻿//Install-Package Microsoft.EntityFrameworkCore.Design -Version 8.0.3
//Install-Package Microsoft.EntityFrameworkCore.Tools -Version 8.0.3
//Install-Package Pomelo.EntityFrameworkCore.MySql -Version 8.0.3
//dotnet ef dbcontext scaffold "Server=localhost;Database=MovieDB;User=root;Password=123456"Pomelo.EntityFrameworkCore.MySql -o Models -c MovieDbContext --force
//# 创建迁移 dotnet ef migrations Add AddRatingToMovie
//# 应用迁移到数据库 dotnet ef database update
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MovieDB.Models; // 根据您的实际命名空间调整
using System;
using System.Threading.Tasks;

// 创建主机构建器
var builder = Host.CreateApplicationBuilder(args);

// 添加配置
builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

// 配置数据库上下文 - 从配置文件读取连接字符串
builder.Services.AddDbContext<MovieDbContext>(options =>
    options.UseMySql(
        builder.Configuration.GetConnectionString("DefaultConnection"),
        ServerVersion.AutoDetect(builder.Configuration.GetConnectionString("DefaultConnection"))
    )
);

// 注册 MovieService
builder.Services.AddScoped<MovieService>();

// 构建主机
var host = builder.Build();

// 运行应用程序
await RunApplication(host);

static async Task RunApplication(IHost host)
{
    Console.WriteLine("开始测试电影数据库操作...");

    try
    {
        // 从依赖注入容器获取 MovieService
        using var scope = host.Services.CreateScope();
        var movieService = scope.ServiceProvider.GetRequiredService<MovieService>();


        // 测试基本 CRUD 操作
        await TestBasicOperations(movieService);

        // 测试复杂查询
        await TestComplexQueries(movieService);

        // 测试参与关系
        await TestParticipationOperations(movieService);

        Console.WriteLine("所有测试完成！");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"应用程序运行失败: {ex.Message}");
        Console.WriteLine($"详细错误: {ex.InnerException?.Message}");
    }

    Console.WriteLine("按任意键退出...");
    Console.ReadKey();
}


static async Task TestBasicOperations(MovieService movieService)
{
    Console.WriteLine("\n=== 测试基本 CRUD 操作 ===");

    // 1. 添加电影
    Console.WriteLine("1. 添加电影...");
    var movie1 = await movieService.AddMovieAsync(
        "肖申克的救赎",
        new DateTime(1994, 9, 23),
        142,
        "英语",
        "希望让人自由",
        9.3f
    );
    Console.WriteLine($"   添加电影成功: {movie1.Name} (ID: {movie1.Id})");

    var movie2 = await movieService.AddMovieAsync(
        "阿凡达",
        new DateTime(2009, 12, 18),
        162,
        "英语",
        "科幻史诗电影",
        7.8f
    );
    Console.WriteLine($"   添加电影成功: {movie2.Name} (ID: {movie2.Id})");

    // 2. 添加艺人
    Console.WriteLine("\n2. 添加艺人...");
    var artist1 = await movieService.AddArtistAsync(
        "蒂姆·罗宾斯",
        new DateTime(1958, 10, 16),
        "M",
        "nm0000209",
        "美国男演员"
    );
    Console.WriteLine($"   添加艺人成功: {artist1.Name} (ID: {artist1.Id})");

    var artist2 = await movieService.AddArtistAsync(
        "摩根·弗里曼",
        new DateTime(1937, 6, 1),
        "M",
        "nm0000151",
        "美国男演员、导演"
    );
    Console.WriteLine($"   添加艺人成功: {artist2.Name} (ID: {artist2.Id})");

    // 3. 查询操作
    Console.WriteLine("\n3. 查询操作测试...");

    // 查询所有电影
    var allMovies = await movieService.GetAllMoviesAsync();
    Console.WriteLine($"   数据库中共有 {allMovies.Count} 部电影");

    // 查询高评分电影
    var highRatedMovies = await movieService.GetMoviesByRatingAsync(8.0f);
    Console.WriteLine($"   评分8.0以上的电影有 {highRatedMovies.Count} 部");

    // 根据名称查询艺人
    var artists = await movieService.GetArtistsByNameAsync("摩根");
    Console.WriteLine($"   包含'摩根'的艺人有 {artists.Count} 位");

    // 4. 更新操作
    Console.WriteLine("\n4. 更新操作测试...");
    var updateResult = await movieService.UpdateMovieAsync(movie2.Id, rating: 8.2f);
    if (updateResult)
    {
        Console.WriteLine($"   成功更新电影 {movie2.Name} 的评分");
    }

    // 5. 验证数据
    Console.WriteLine("\n5. 数据验证...");
    var updatedMovie = await movieService.GetMovieByIdAsync(movie2.Id);
    if (updatedMovie != null)
    {
        Console.WriteLine($"   电影 {updatedMovie.Name} 的最新评分为: {updatedMovie.Rating}");
    }
}

static async Task TestComplexQueries(MovieService movieService)
{
    Console.WriteLine("\n=== 测试复杂查询 ===");

    // 查询所有电影并显示详细信息
    var movies = await movieService.GetAllMoviesAsync();
    Console.WriteLine("电影列表:");
    foreach (var movie in movies)
    {
        Console.WriteLine($"   - {movie.Name} ({movie.Releasedate?.Year}), 评分: {movie.Rating}, 时长: {movie.Duration}分钟");
    }

    // 查询所有艺人
    var artists = await movieService.GetAllArtistsAsync();
    Console.WriteLine($"艺人列表 (共{artists.Count}位):");
    foreach (var artist in artists.Take(5)) // 只显示前5位
    {
        Console.WriteLine($"   - {artist.Name} ({artist.Birthday?.Year}), {artist.Introduction}");
    }
}

static async Task TestParticipationOperations(MovieService movieService)
{
    Console.WriteLine("\n=== 测试参与关系操作 ===");

    try
    {
        // 获取现有的电影和艺人（假设之前已经创建了）
        var movies = await movieService.GetAllMoviesAsync();
        var artists = await movieService.GetAllArtistsAsync();

        if (movies.Count >= 2 && artists.Count >= 2)
        {
            var movie1 = movies[0];
            var movie2 = movies[1];
            var artist1 = artists[0];
            var artist2 = artists[1];

            // 添加参与关系
            Console.WriteLine("1. 添加参与关系...");
            await movieService.AddParticipationAsync(artist1.Id, movie1.Id, "安迪·杜佛兰");
            await movieService.AddParticipationAsync(artist2.Id, movie1.Id, "埃利斯·波伊德·雷丁");
            await movieService.AddParticipationAsync(artist1.Id, movie2.Id, "主角");

            Console.WriteLine("   参与关系添加成功");

            // 查询电影的参与者
            Console.WriteLine("\n2. 查询电影参与者...");
            var participants = await movieService.GetMovieParticipantsAsync(movie1.Id);
            Console.WriteLine($"   电影 '{movie1.Name}' 的参与者:");
            foreach (var participant in participants)
            {
                Console.WriteLine($"      - {participant.ArtistName} 饰演 {participant.RoleName}");
            }

            // 查询艺人的电影
            Console.WriteLine("\n3. 查询艺人参与的电影...");
            var artistMovies = await movieService.GetArtistMoviesAsync(artist1.Id);
            Console.WriteLine($"   艺人 '{artist1.Name}' 参与的电影:");
            foreach (var movie in artistMovies)
            {
                Console.WriteLine($"      - {movie.MovieName} ({movie.ReleaseDate?.Year}), 评分: {movie.Rating}, 角色: {movie.RoleName}");
            }
        }
        else
        {
            Console.WriteLine("   需要至少2部电影和2位艺人来测试参与关系");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"   参与关系测试失败: {ex.Message}");
    }
}